package xyz.herz.cts;

import org.apache.catalina.valves.ParameterLimitValve;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

@Configuration
public class MultipartConfig {

// 注入bean即可  解决  org.apache.tomcat.util.http.fileupload.impl.FileCountLimitExceededException: attachment
    // 显式注册了 CommonsMultipartResolver，覆盖了 Spring Boot 默认使用的 StandardServletMultipartResolver
    // 但是 Tomcat 原生配置的文件大小限制就不会生效。
    // 只有生效  spring:
    //  servlet:
    //    multipart:
    //      max-file-size: 10MB
    //      max-request-size: 50MB


//    @Bean
//    public CommonsMultipartResolver multipartResolver() {
//
//        CommonsMultipartResolver resolver = new CommonsMultipartResolver();
//
//        return resolver;
//    }

    //
    @Bean
    public TomcatServletWebServerFactory servletContainer() {
        return new TomcatServletWebServerFactory() {
            @Override
            protected void postProcessContext(org.apache.catalina.Context context) {
                context.setAddWebinfClassesResources(true);

                // ✅ 关键：通过 Valve 配置 fileCountMax
                ParameterLimitValve valve = new ParameterLimitValve();
                // 直接设置限制，例如允许最大参数数10000，最大文件数10000
                valve.setUrlPatternLimits(".*=10000,10000,4096"); // 格式：urlRegex=paramCount,partCount,partHeaderSize
                context.getPipeline().addValve(valve);
            }
        };
    }



}
